package com.xuecheng.learning.service.impl;

import cn.hutool.db.sql.Order;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.xuecheng.commons.constants.CourseConstants;
import com.xuecheng.commons.constants.OrdersConstants;
import com.xuecheng.commons.enums.ErrorCode;
import com.xuecheng.commons.model.dto.LearningProgressDto;
import com.xuecheng.commons.model.dto.RecordDto;
import com.xuecheng.commons.model.vo.*;
import com.xuecheng.commons.utils.AuthInfoHolder;
import com.xuecheng.commons.utils.BeanHelper;
import com.xuecheng.content.api.ContentClient;
import com.xuecheng.learning.domain.CourseRecord;
import com.xuecheng.learning.mappers.CourseRecordMapper;
import com.xuecheng.learning.service.CourseRecordService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.xuecheng.media.api.MediaClient;
import com.xuecheng.web.exceptions.BusinessException;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.Date;

/**
 * 选课记录 服务实现类
 */
@Service
public class CourseRecordServiceImpl extends ServiceImpl<CourseRecordMapper, CourseRecord> implements CourseRecordService {

    @Autowired
    private ContentClient contentClient;

    //通过课程发布id查询用户的课程记录
    @Override
    public ResponseResult<CourseRecordVo> findRecordByPubId(Long coursePubId) {
        //1.设置查询条件
        LambdaQueryWrapper<CourseRecord> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(CourseRecord::getCoursePubId, coursePubId);
        wrapper.eq(CourseRecord::getUserId, AuthInfoHolder.getUserId());
        CourseRecord courseRecord = getOne(wrapper);
        //2.若为空，证明还没有学习，直接返回
        if (courseRecord == null) {
            return ResponseResult.okResult();
        }
        //3.不为空时，将CourseRecord对象转换为vo对象返回
        CourseRecordVo vo = BeanHelper.copyProperties(courseRecord, CourseRecordVo.class);
        return ResponseResult.okResult(vo);
    }
    //保存或更新选课记录
    @Override
    public ResponseResult saveRecord(RecordDto dto) {
        //1.根据课程发布id和用户id查询选课记录
        LambdaQueryWrapper<CourseRecord> qw = new LambdaQueryWrapper<>();
        qw.eq(CourseRecord::getCoursePubId, dto.getCoursePubId());
        qw.eq(CourseRecord::getUserId, dto.getUserId());
        CourseRecord record = getOne(qw);
        //2.如果不为空：更改支付状态为已支付
        if (record != null) {
            record.setPaid(OrdersConstants.PAID);
            updateById(record);
        } else {
            //3.如果为空，向选课记录表中保存
            //根据内容微服务查询课程发布信息
            ResponseResult<CoursePubVo> result = contentClient.findById(dto.getCoursePubId());
            CoursePubVo data = result.getData();
            record = new CourseRecord();
            record.setUserId(dto.getUserId());
            record.setCoursePubId(dto.getCoursePubId());
            record.setCompanyId(data.getCompanyId());
            record.setCourseId(data.getCourseId());
            record.setCoursePubName(data.getName());
            record.setTeachmode(data.getTeachmode());
            record.setStartTime(data.getStartTime());
            record.setEndTime(data.getEndTime());
            record.setCreateDate(new Date());
            record.setPaid(OrdersConstants.PAID);
            boolean save = save(record);
            if (!save) {
                throw new BusinessException(ErrorCode.DATAERROR);
            }
        }
        return ResponseResult.okResult();
    }

    @Autowired
    private MediaClient mediaClient;

    //获取课程视频资源地址
    @Override
    public ResponseResult<ResourceVo> findPlayUrl(Long coursePubId, Long mediaId, Long teachplanId) {
        //1.根据coursePubId查询课程发布数据
        ResponseResult<CoursePubVo> pubResult = contentClient.findById(coursePubId);
        CoursePubVo pubVo = pubResult.getData();
        String charge = pubVo.getCharge();
        //如果课程收费
        if (charge.equals(CourseConstants.CHARGE_YES)) {
            //2.根据teachplanId查询章节
            ResponseResult<TeachplanVo> teachplanResult = contentClient.findPlanById(teachplanId);
            String preview = teachplanResult.getData().getIsPreview();
            //如果章节收费
            if (preview.equals("0")) {
                //3.查询课程记录
                LambdaQueryWrapper<CourseRecord> qw = new LambdaQueryWrapper<>();
                qw.eq(CourseRecord::getCoursePubId,coursePubId);
                qw.eq(CourseRecord::getUserId,AuthInfoHolder.getUserId());
                CourseRecord record = getOne(qw);
                //如果课程记录不存在，或者未支付，则抛异常
                if (record == null || record.getPaid().equals(OrdersConstants.NOT_PAID)) {
                    throw new BusinessException(ErrorCode.ERROR);
                }
            }
        }
        return mediaClient.findMediaUrl(mediaId);
    }
    //保存或更新学习进度
    @Override
    public ResponseResult progress(LearningProgressDto dto) {
        //1.根据coursePubId查询学习记录
        LambdaQueryWrapper<CourseRecord> qw = new LambdaQueryWrapper<>();
        qw.eq(CourseRecord::getCoursePubId,dto.getCoursePubId());
        qw.eq(CourseRecord::getUserId,AuthInfoHolder.getUserId());
        CourseRecord record = getOne(qw);
        //2.如果存在，更新进度
        if (record != null) {
            record.setTeachplanId(dto.getTeachPlanId());
            record.setTeachplanName(dto.getTeachPlanName());
            updateById(record);
        } else {
            //3.如果不存在
            //3-1 查询课程发布数据
            ResponseResult<CoursePubVo> result = contentClient.findById(dto.getCoursePubId());
            CoursePubVo coursePubVo = result.getData();
            //3-2 创建记录对象并保存
            record= new CourseRecord();
            record.setUserId(AuthInfoHolder.getUserId());
            record.setCompanyId(coursePubVo.getCompanyId());
            record.setCourseId(coursePubVo.getCourseId());
            record.setCoursePubId(dto.getCoursePubId());
            record.setCoursePubName(coursePubVo.getName());
            record.setTeachmode(coursePubVo.getTeachmode());
            record.setStartTime(coursePubVo.getStartTime());
            record.setEndTime(coursePubVo.getEndTime());
            record.setTeachplanId(dto.getTeachPlanId());
            record.setTeachplanName(dto.getTeachPlanName());
            record.setCreateDate(new Date());
            record.setPaid(OrdersConstants.PAID);
            save(record);
        }
        return ResponseResult.okResult();
    }
}
